package org.jeecg.modules.wechat.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.PullSmsSendStatusRequest;
import com.tencentcloudapi.sms.v20210111.models.PullSmsSendStatusResponse;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.jeecg.common.util.SpringContextHolder;
import org.jeecg.modules.send_msg_config.entity.SendMsgConfig;
import org.jeecg.modules.send_msg_config.service.ISendMsgConfigService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;


@Component
public class SendSmsUtil extends HttpServlet {
    private static ApplicationContext applicationContext;


    // public static final String SecretId="AKID4ybx3tSkmX0C7l8E3cvxiDTSAbVEmAKE";
    // public static final String SecretKey="f4E8mAJDsHQJwJQJxLTMzMTLyOZVCcmg";
    // public static final String templateId="88529";
    //public static final String sdkAppId="1400835338";
    // public static final String signName="安好康护";


//    public static final String SecretId="AKIDCHArLbdS5VhgRiqnZ7TeCcrunSyKUSCj";
//    public static final String SecretKey="NwIRN9h3C8sQr56tUswrZ3KXp14uWu5L";
//    public static final String sdkAppId="1401002775";
//    public static final String signName="华声健康医疗";
//    public static final String templateId="185959";

    public static final String SecretId="AKID4ybx3tSkmX0C7l8E3cvxiDTSAbVEmAKE";
    public static final String SecretKey="4331ff2133a3e41aba5a7015950c6eae";
    public static final String sdkAppId="1401021786";
    public static String signName="广西安好医院";
    public static final String templateId="88529";

    public ServletContext getServletContext() {
        // 先获取 Spring 的 Web 上下文
        WebApplicationContext webContext = (WebApplicationContext) SpringContextHolder.getApplicationContext();
        // 从 Web 上下文中获取 ServletContext
        ServletContext servletContext = webContext.getServletContext();
        return servletContext;
    }

    public static boolean sendMsg(String[] phoneNumberSet, String[] templateParamSet, String sysOrg) throws TencentCloudSDKException {

        String SecretId;
        String SecretKey;
        String sdkAppId;
        String signName;
        String templateId;
        try {
            WebApplicationContext webContext = (WebApplicationContext) SpringContextHolder.getApplicationContext();
            // 从 Web 上下文中获取 ServletContext
            ServletContext servletContext = webContext.getServletContext();
            System.out.println("sysOrg:1111111111111111111"+sysOrg);
            if(sysOrg != null && sysOrg.length() >=6){

                // 从 ServletContext 中获取 WebApplicationContext（继承自 ApplicationContext）
                WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);

                // 获取 Bean
                ISendMsgConfigService service = context.getBean(ISendMsgConfigService.class);


                SendMsgConfig config=service.getOne(new QueryWrapper<SendMsgConfig>().eq("sys_org",sysOrg.substring(0,6)));
                SecretId=config.getSecretId();
                SecretKey=config.getSecretKey();
                sdkAppId=config.getSdkAppid();
                signName=config.getSignName();
                templateId = config.getTemplateId();
            }
            else{
                throw new Exception("请在发送短信配置表请填入正确机构编码！");
            }
            Credential cred = new Credential(SecretId, SecretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("GET"); // get请求(默认为post请求)
            httpProfile.setConnTimeout(10); // 请求连接超时时间，单位为秒(默认60秒)
            httpProfile.setWriteTimeout(10);  // 设置写入超时时间，单位为秒(默认0秒)
            httpProfile.setReadTimeout(10);  // 设置读取超时时间，单位为秒(默认0秒)
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppId(sdkAppId);
            req.setSignName(signName);
            req.setTemplateId(templateId);
            req.setTemplateParamSet(templateParamSet);
            req.setPhoneNumberSet(phoneNumberSet);
            String sessionContext = "";
            req.setSessionContext(sessionContext);
            String extendCode = "";
            req.setExtendCode(extendCode);
            String senderid = "";
            req.setSenderId(senderid);
            SendSmsResponse res = client.SendSms(req);
            if ("Ok".equals(res.getSendStatusSet()[0].getCode())) {
                return true;
            }

        } catch (TencentCloudSDKException e) {
            System.out.println("发送短信错误信息"+e.getMessage());
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return false;
    }

    public static void PullSmsSendStatus(String[] phoneNumberSet,String[] templateParamSet){
        try {
            Credential cred = new Credential(System.getenv("TENCENTCLOUD_SECRET_ID"), System.getenv("TENCENTCLOUD_SECRET_KEY"));

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("GET"); // get请求(默认为post请求)
            httpProfile.setConnTimeout(30); // 请求连接超时时间，单位为秒(默认60秒)
            httpProfile.setWriteTimeout(30);  // 设置写入超时时间，单位为秒(默认0秒)
            httpProfile.setReadTimeout(30);  // 设置读取超时时间，单位为秒(默认0秒)

            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            PullSmsSendStatusRequest req = new PullSmsSendStatusRequest();
            req.setSmsSdkAppId(sdkAppId);
            // 设置拉取最大条数，最多100条
            Long limit = 5L;
            req.setLimit(limit);
            PullSmsSendStatusResponse res = client.PullSmsSendStatus(req);
            System.out.println(PullSmsSendStatusResponse.toJsonString(res));
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
    }
}
